package top.gbiot.config.mqtt;

import org.apache.ibatis.session.SqlSessionFactory;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
import top.gbiot.common.AppConstant;

/**
 * @author 耿彬
 * @desc 消息接收监听类
 * @date 2020年11月21日 15:24
 **/
@Component
public class PushCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);

    @Autowired
    private MqttConfig mqttConfig;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
//    @Autowired
//    private IotDeviceDao iotDeviceDao;
    //批量插入
    @Autowired
    private SqlSessionFactory sqlSessionFactory;


    private static MqttClient client;

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，可以做重连");
        if (client == null || !client.isConnected()) {
            try {
                logger.info("5S后重连.......");
                Thread.sleep(5000);
                mqttConfig.getMqttPushClient();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        //特别注意一下，messageArrived这个里面不允许调用代码和写方法，如果调用就会断开连接这个是个坑，然后用我这个try{}catch{}就没有问题了，就不会再去掉线断开连接
        //DataObject payloadData = new DataObject(JsonUtil.jsonToMap(new String(mqttMessage.getPayload())));
        logger.info("接收消息主题 : " + topic);
        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));
        //activeMq转发
        jmsMessagingTemplate.convertAndSend(AppConstant.MQ_QUEUE_NAME, new String(mqttMessage.getPayload()));
    }


    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }
}
